package com.star.es.entity;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import org.elasticsearch.action.search.SearchAction;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * ES查询封装
 * 
 * @author Administrator SearchRequestBuilder常用方法说明：
 *         https://blog.csdn.net/lu_wei_wei/article/details/51034211
 */
@Slf4j
@Data
@SuppressWarnings("serial")
public class ESSearchBuilder implements Serializable {

	private TransportClient client;
	private ESQuery esQuery;
	private SearchRequestBuilder requestBuilder;

	public ESSearchBuilder(TransportClient client, ESQuery esQuery) {
		super();
		this.client = client;
		this.esQuery = esQuery;
		this.requestBuilder = new SearchRequestBuilder(client, SearchAction.INSTANCE);
	}

	/**
	 * 单文档查询
	 * @return
	 */
	public SearchResponse build() {
		// 索引 index
		String[] indexs = new String[esQuery.getIndexs().size()];
		if (indexs.length < 0) {
			log.error("索引值不能为空！");
		}
		requestBuilder.setIndices(esQuery.getIndexs().toArray(indexs));
		// type
		String[] types = new String[esQuery.getTypes().size()];
		if (types.length > 0) {
			requestBuilder.setTypes(esQuery.getTypes().toArray(types));
		}
		// searchType搜索类型
		requestBuilder.setSearchType(esQuery.getSearchType());
		// Query查询条件
		if (null != esQuery.getQuery()) {
			requestBuilder.setQuery(esQuery.getQuery());
		}else{ // 查询所有
			requestBuilder.setQuery(QueryBuilders.matchAllQuery());
		}
		// Filter过滤条件
		if (null != esQuery.getFilter()) {
			requestBuilder.setPostFilter(esQuery.getFilter());
		}
		// 聚合查询，类似Solr的facet查询
		if (esQuery.getAggregations().size() > 0) {
			esQuery.getAggregations().forEach(aggregation -> {
				requestBuilder.addAggregation(aggregation);
			});
		}
		// Score得分最少数量
		if (esQuery.getMinScore() > 0.0) {
			requestBuilder.setMinScore(esQuery.getMinScore());
		}
		// From页码
		requestBuilder.setFrom(esQuery.getFrom());
		// Size每页数量
		requestBuilder.setSize(esQuery.getSize());
		// Timeout超时时间
		requestBuilder.setTimeout(new TimeValue(esQuery.getTimeout(), TimeUnit.SECONDS));

		// explain
		requestBuilder.setExplain(true);
		return requestBuilder.get();
	}

}
